package com.zsc.oj.job.once.schedul;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zsc.oj.constant.PostThumbRedisConstant;
import com.zsc.oj.model.entity.PostThumb;
import com.zsc.oj.model.entity.User;
import com.zsc.oj.service.PostThumbService;
import com.zsc.oj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SyncRedisToMysql {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private PostThumbService postThumbService;

    @Resource
    private UserService userService;

    @Scheduled(fixedRate = 30 * 1000)
    public void sync(){
        List<User> userList = userService.list();
        List<Long> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());
        for (Long userId : userIdList) {
            RSet<Long> set = redissonClient.getSet(PostThumbRedisConstant.getUserKey(userId));
            Set<Long> posIdtSet = set.readAll();

            for (Long postId : posIdtSet) {
                this.addToMysql(userId,postId);
            }
        }
        log.info("完成redis到mysql的同步");
    }

    public void addToMysql(Long userId,Long postId){
        QueryWrapper<PostThumb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("postId",postId);
        PostThumb one = postThumbService.getOne(queryWrapper);
        if(one == null){
            PostThumb postThumb = new PostThumb();
            postThumb.setUserId(userId);
            postThumb.setPostId(postId);
            postThumbService.save(postThumb);
        }
    }
}
